package common

import (
	"GoAdmin/model"
	"github.com/dgrijalva/jwt-go"
	"time"
)

var jwtKey = []byte("a_secret_crect")

type Claims struct {
	UserId uint
	jwt.StandardClaims
}

func ReleaseToken(user model.User) (string, error) {
	//设置token有效期限为七天
	expirationTime := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		UserId: user.ID,
		StandardClaims: jwt.StandardClaims{
			//这地方可以随意定义
			ExpiresAt: expirationTime.Unix(),
			IssuedAt:  time.Now().Unix(),
			//谁发放了这个Token
			Issuer: "com.jingsong.ltd",
			//主题
			Subject: "user token",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	//使用jwttoken密钥来生成token
	tokenString, error := token.SignedString(jwtKey)
	//如果和生成错误，将这个错误返回
	if error != nil {
		return "", error
	}
	return tokenString, nil
}

func ParserToken(tokenString string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}
	//解析Token
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})

	return token, claims, err
}
